package com.dianmi.seckill.common.advice;

import com.dianmi.seckill.common.utils.JsonUtil;
import com.google.common.collect.ImmutableSet;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Set;

/**
 * @author xieqiaofu
 * @date 2020/11/24
 */
@RestControllerAdvice
@ControllerAdvice
public class GlobalResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    private final Set<Object> jsonMediaType;

    public GlobalResponseBodyAdvice() {
        this.jsonMediaType = (new ImmutableSet.Builder()).add(MediaType.APPLICATION_JSON_UTF8).add(MediaType.APPLICATION_JSON).build();
    }

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (!jsonMediaType.contains(selectedContentType) || body instanceof ResponseData) {
            return body;
        }
        ResponseData<Object> responseData = ResponseData.success(body);
        //当返回string类型时，需要手动序列化再返回
        if (isSimpleType(returnType)) {
            return JsonUtil.toJson(responseData);
        }
        return responseData;
    }

    private boolean isSimpleType(MethodParameter returnType) {
        return returnType.getMethod().getReturnType() == String.class;
    }
}
